//
//  JHBookUnitDetailViewController.m
//  JuniRengLish_iOS
//
//  Created by Maiyou on 2019/5/16.
//  Copyright © 2019 revogi. All rights reserved.
//

#import "JHBookUnitDetailViewController.h"
#import "JHBookUnitDetailView.h"
#import "JHPreferencesViewController.h"
#import "JHPreferencesInfoModel.h"
#import "JHFocusExplanationViewController.h"
#import "JHPracticeDataModel.h"
#import "JHPracticeDataViewController.h"
#import "JHMyNewWordsListController.h"

@interface JHBookUnitDetailViewController () <UIScrollViewDelegate, JHBookUnitDetailViewDelegate>

@property (nonatomic, strong) YUHoriView * horiView;

@property (nonatomic, strong) UIScrollView * scrollView;

@property (nonatomic, strong) NSMutableArray * titleArray;
@property (nonatomic, strong) NSMutableArray * playerArray;
@property (nonatomic, strong) AVPlayer * currentPlayer;
@property (nonatomic, assign) BOOL isBook;
@property (nonatomic, strong) NSTimer * serverTimer;
@property (nonatomic, strong) UIButton * selectedButton;

@property (nonatomic, assign) NSInteger selectedIndex;
@property (weak, nonatomic) IBOutlet UIButton *switchViewBtn;
@property (weak, nonatomic) IBOutlet UIButton *playerBtn;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
//定时计时
@property (nonatomic, assign) NSInteger timeCount;
@property (nonatomic, assign) NSInteger addCount;
/**  是否有练习  */
@property (nonatomic, assign) BOOL isPractice;

@end

@implementation JHBookUnitDetailViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.titleArray = [NSMutableArray array];
    self.playerArray = [NSMutableArray array];
    if (self.bookItemModel)
    {
        for (JHBookItemDataModel * model in self.bookItemModel.data) {
            [self.titleArray addObject:model.titlename];
        }
        self.isBook = YES;
        self.navigationItem.title = self.bookItemModel.unitname;
        
        if (self.bookItemModel.practerm == nil || self.bookItemModel.pracunit == nil ||  self.bookItemModel.practerm.integerValue == -1 || self.bookItemModel.pracunit.integerValue == -1) {
            self.isPractice = NO;
        }else{
            self.isPractice = YES;
        }
    }
    else
    {
        for (JHWordItemDataModeel * model in self.wordItemModel.data) {
            [self.titleArray addObject:model.titlename];
        }
        self.isBook = NO;
        self.navigationItem.title = self.wordItemModel.unitname;
        
        if (self.bookItemModel.practerm == nil || self.bookItemModel.pracunit == nil || self.wordItemModel.practerm.integerValue == -1 || self.wordItemModel.pracunit.integerValue == -1) {
            self.isPractice = NO;
        }else{
            self.isPractice = YES;
        }
    }
    self.horiView.titles = self.titleArray;
    [self.horiView refresh];
    
    [self.view addSubview:self.scrollView];
    
    [self.serverTimer fire];
    
    [self addNavRightButton];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
//    [self.currentPlayer pause];
//    self.selectedButton.selected = NO;
    if ([JHDeviceInfoTool sharedManager].currentPlayer != self.currentPlayer) {
        [[JHDeviceInfoTool sharedManager].currentPlayer pause];
    }
    [JHDeviceInfoTool sharedManager].currentPlayer = self.currentPlayer;
    [JHDeviceInfoTool sharedManager].currentVC = self;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"GetPlayerStatus" object:@(self.selectedButton.selected)];
}

- (NSTimer *)serverTimer
{
    if (nil == _serverTimer)
    {
        _serverTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(showServerLoading) userInfo:nil repeats:YES];
        NSRunLoop *curRun = [NSRunLoop currentRunLoop];
        [curRun addTimer:_serverTimer forMode:NSRunLoopCommonModes];
    }
    return _serverTimer;
}

- (void)addNavRightButton
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 44)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    
    UIButton * rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(view.width - 45, 0, 50, 44)];
    rightBtn.tag = 10;
    rightBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    rightBtn.titleLabel.font = [UIFont boldSystemFontOfSize:13];
    [rightBtn addTarget:self action:@selector(rightNavButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:rightBtn];
    
    UIButton * leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35, 44)];
    leftBtn.tag = 20;
    leftBtn.titleLabel.font = [UIFont boldSystemFontOfSize:13];
    [leftBtn setTitle:@"练习" forState:0];
    [leftBtn addTarget:self action:@selector(rightNavButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:leftBtn];
    
    if (self.isBook)
    {
        if (self.isPractice)//练习
        {
            [rightBtn setTitle:@"练习" forState:0];
            [leftBtn setTitle:@"讲解" forState:0];
        }
        else//讲解
        {
            [rightBtn setTitle:@"讲解" forState:0];
            leftBtn.hidden = YES;
            view.width = 45;
            rightBtn.x = 0;
        }
    }
    else//生词本
    {
        if (self.isPractice)//练习
        {
            [rightBtn setTitle:@"生词本" forState:0];
            [leftBtn setTitle:@"练习" forState:0];
        }
        else//讲解
        {
            [rightBtn setTitle:@"生词本" forState:0];
            leftBtn.hidden = YES;
            view.width = 45;
            rightBtn.x = 0;
        }
    }
}

- (void)rightNavButtonClick:(UIButton *)sender
{
    if (sender.tag == 10)
    {
        if (self.isBook)
        {
            if (self.isPractice)//练习
            {
                [self pushToPracticeVc];
            }
            else//讲解
            {
                JHFocusExplanationViewController * vc = [JHFocusExplanationViewController new];
                vc.navTitle = [NSString stringWithFormat:@"重点讲解-%@", self.bookItemModel.explainname];
                vc.urlPath = [NSString stringWithFormat:@"%@/%@/%@", [JHFileManger getDocumentsPath], self.bookId, self.bookItemModel.explainname];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
        else//生词本
        {
            [self.navigationController pushViewController:[JHMyNewWordsListController new] animated:YES];
        }
    }
    else
    {
        if (self.isBook)
        {
            if (self.isPractice)//讲解
            {
                JHFocusExplanationViewController * vc = [JHFocusExplanationViewController new];
                vc.navTitle = [NSString stringWithFormat:@"重点讲解-%@", self.bookItemModel.explainname];
                vc.urlPath = [NSString stringWithFormat:@"%@/%@/%@", [JHFileManger getDocumentsPath], self.bookId, self.bookItemModel.explainname];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
        else
        {
            if (self.isPractice)//练习
            {
                [self pushToPracticeVc];
            }
        }
    }
}

- (void)pushToPracticeVc
{
    NSArray * array = [self getAllPracticeData];
    if (array.count > 0)
    {
        JHPracticeDataViewController * practice = [JHPracticeDataViewController new];
        practice.dataArray = array;
        [self.navigationController pushViewController:practice animated:YES];
    }
    else
    {
        [DJToast showBottomToast:@"暂无练习~"];
    }
}

- (void)showServerLoading
{
    if (self.currentPlayer)
    {
        //进度 当前时间/总时间
        CGFloat progress = CMTimeGetSeconds(self.currentPlayer.currentItem.currentTime) / CMTimeGetSeconds(self.currentPlayer.currentItem.duration);
        self.progressView.progress = progress;
        
        //定时
        if (self.timeCount > 0)
        {
            self.addCount ++;
            if (self.addCount > self.timeCount)
            {
                self.playerBtn.selected = NO;
                [self.currentPlayer pause];
                self.timeCount = 0;
                self.addCount = 0;
            }
        }
    }
}

- (YUHoriView *)horiView
{
    if (!_horiView)
    {
        WEAKSELF
        _horiView = [[YUHoriView alloc] initWithFrame:CGRectMake(0, 0, JKScreenW, 50)];
        _horiView.backgroundColor = JKMainColor;
        _horiView.defaultButtonPos = 0;
        _horiView.ySpan = 10;
        _horiView.xSpan = 15;
        _horiView.onPosChange = ^(YUHoriElementButton *sender, int pos, NSString *title)
        {
            NSLog(@"pos: %d ,title :%@", pos, title);
            weakSelf.selectedIndex = pos;
            weakSelf.scrollView.contentOffset = CGPointMake(JKScreenW * pos, 0);
        };
        [self.view addSubview:_horiView];
    }
    return _horiView;
}

- (UIScrollView *)scrollView
{
    if (!_scrollView)
    {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 50, JKScreenW, JKScreenH - kStatusBarAndNavigationBarHeight - kTabbarSafeBottomMargin - 60 - 50)];
        _scrollView.contentSize = CGSizeMake(JKScreenW * self.titleArray.count, _scrollView.height);
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
        _scrollView.showsHorizontalScrollIndicator = NO;
        
        //当标题少于两个隐藏
        if (self.titleArray.count < 2)
        {
            _scrollView.y = 0;
            _scrollView.height += 50;
            self.horiView.hidden = YES;
        }
        for (int i = 0; i < self.titleArray.count; i ++)
        {
            JHBookUnitDetailView * unitView = [[JHBookUnitDetailView alloc] initWithFrame:CGRectMake(JKScreenW * i, 0, JKScreenW, _scrollView.height)];
            unitView.delegate = self;
            if (self.isBook)
            {
                JHBookItemDataModel * model = self.bookItemModel.data[i];
                unitView.textFileName = model.textfile;
                unitView.mp3Name = model.mp3name;
            }
            else
            {
                JHWordItemDataModeel * model = self.wordItemModel.data[i];
                unitView.textFileName = model.textfile;
                unitView.mp3Name = model.mp3name;
            }
            unitView.tag = i + 100;
            unitView.isBook = self.isBook;
            unitView.bookid = self.bookId;
            unitView.currentVC = self;
            [_scrollView addSubview:unitView];
            
            [self.playerArray addObject:unitView.player];
        }
    }
    return _scrollView;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = scrollView.contentOffset.x / JKScreenW;
    self.selectedIndex = index;
    [self.horiView selectPos:index];
}

- (void)playEnd:(id)unitView
{
    if ([JHPreferencesInfoModel shareInstance].playMode == 31)
    {
        JHBookUnitDetailView * view = unitView;
        AVPlayerItem * item = view.player.currentItem;
        [item seekToTime:kCMTimeZero];
        self.selectedButton.selected = NO;
    }
    else if ([JHPreferencesInfoModel shareInstance].playMode == 32)
    {
        JHBookUnitDetailView * view = unitView;
        NSInteger index = view.tag - 100 + 1;
        
        if (index < self.titleArray.count)
        {
            self.scrollView.contentOffset = CGPointMake(JKScreenW * index, 0);
            [self.horiView selectPos:index];
            self.selectedIndex = index;
            
            JHBookUnitDetailView * unitView = [self.view viewWithTag:index + 100];
            self.currentPlayer = unitView.player;
            AVPlayerItem * item = unitView.player.currentItem;
            [item seekToTime:kCMTimeZero];
            [unitView.player play];
        }
        else
        {
            JHBookUnitDetailView * view = unitView;
            AVPlayerItem * item = view.player.currentItem;
            [item seekToTime:kCMTimeZero];
            self.selectedButton.selected = NO;
        }
    }
}

- (void)selectRowPlay:(AVPlayer *)player
{
    if (player != self.currentPlayer)
    {
        [self.currentPlayer pause];
    }
    self.playerBtn.selected = YES;
    self.currentPlayer = player;
}

#pragma mark - 播放/暂停
- (IBAction)playBtnClick:(id)sender
{
    UIButton *button = sender;
    AVPlayer * player = self.playerArray[self.selectedIndex];
    if (player == self.currentPlayer)
    {
        (button.isSelected) ? [player pause] : [player play];
        button.selected = !button.selected;
    }
    else
    {
        button.selected = YES;
        [self.currentPlayer pause];
        [player play];
        self.currentPlayer = player;
        //关闭从首页直接点击进来的player
        if ([JHDeviceInfoTool sharedManager].currentPlayer != self.currentPlayer) {
            [[JHDeviceInfoTool sharedManager].currentPlayer pause];
        }
    }
    self.selectedButton = button;
}
#pragma mark - 设置
- (IBAction)settingBtnClick:(id)sender
{
    JHPreferencesViewController * preferences = [JHPreferencesViewController new];
    preferences.preferencesInfo = ^(NSInteger time, CGFloat rate) {
        for (int i = 0; i < self.titleArray.count; i ++)
        {
            JHBookUnitDetailView * unitView = [self.view viewWithTag:i + 100];
            [unitView.tableView reloadData];
        }
        //定时时间
        self.timeCount = time * 60;
        self.addCount = 1;
        //播放速度
        self.currentPlayer.rate = rate;
    };
    [self.navigationController pushViewController:preferences animated:YES];
}

#pragma mark - 翻译
- (IBAction)translateBtnClick:(id)sender
{
    UIButton * button = sender;
    button.selected = !button.selected;
    for (int i = 0; i < self.titleArray.count; i ++)
    {
        JHBookUnitDetailView * unitView = [self.view viewWithTag:i + 100];
        unitView.isTranslate = !unitView.isTranslate;
        [unitView.tableView reloadData];
    }
}

#pragma mark - 切换界面
- (IBAction)switchViewCilck:(id)sender
{
    
}

- (void)dealloc
{
    if(_serverTimer != nil && [_serverTimer isValid])
        [_serverTimer invalidate];
    
    [self.currentPlayer pause];
    self.currentPlayer = nil;
}

- (NSArray *)getAllPracticeData
{
    NSString * databasePath = [[NSBundle mainBundle] pathForResource:@"juniorhelp_practice09" ofType:@".db"];
    FMDatabaseQueue * dataBaseQueue = [FMDatabaseQueue databaseQueueWithPath:databasePath];
    NSString *sqlString = [NSString stringWithFormat:@"SELECT * from practice where unit = %@ and term = %@", self.isBook ? self.bookItemModel.pracunit : self.wordItemModel.pracunit, self.isBook ? self.bookItemModel.practerm : self.wordItemModel.practerm];
    __block NSMutableArray * array = [NSMutableArray array];
    [dataBaseQueue inDatabase:^(FMDatabase * _Nonnull db) {
        FMResultSet *set = [db executeQuery:sqlString];
        while ([set next])
        {
            NSString * question = [set stringForColumn:@"question"];
            NSString * option1 = [set stringForColumn:@"option1"];
            NSString * option2 = [set stringForColumn:@"option2"];
            NSString * option3 = [set stringForColumn:@"option3"];
            NSString * option4 = [set stringForColumn:@"option4"];
            NSString * explain = [set stringForColumn:@"explain"];
            NSString * answer = [set stringForColumn:@"answer"];
            NSString * unit = [set stringForColumn:@"unit"];
            NSString * term = [set stringForColumn:@"term"];
            
            JHPracticeDataModel * model = [[JHPracticeDataModel alloc] init];
            model.question = [[question URLDecodedString] stringByReplacingOccurrencesOfString:@"+" withString:@" "];
            model.option1 = [[option1 URLDecodedString] stringByReplacingOccurrencesOfString:@"+" withString:@" "];
            model.option2 = [[option2 URLDecodedString]stringByReplacingOccurrencesOfString:@"+" withString:@" "];
            model.option3 = [[option3 URLDecodedString]stringByReplacingOccurrencesOfString:@"+" withString:@" "];
            model.option4 = [[option4 URLDecodedString]stringByReplacingOccurrencesOfString:@"+" withString:@" "];
            model.explain = [[explain URLDecodedString]stringByReplacingOccurrencesOfString:@"+" withString:@" "];
            model.answer = answer;
            model.unit = unit;
            model.term = term;
            [array addObject:model];
        }
        [set close];
    }];
    return array;
}

@end
